package com.coding.beautiful.error;

import com.alibaba.fastjson.JSONObject;
import com.coding.beautiful.util.ResTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class MyControllerAdvice {
    private final static Logger LOGGER = LoggerFactory.getLogger(MyControllerAdvice.class);

    /**
     * 全局异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public JSONObject errorHandler(Exception ex) {
        JSONObject result = new JSONObject();
        LOGGER.info("错误信息:{}", ex);
        result.put("msg", "系统错误，请微信联系管理员");
        result.put("message", ex.getMessage());
        return result;
    }

    /**
     * 参数异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ParamException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JSONObject paramHandler(ParamException ex) {
        JSONObject result = new JSONObject();
        result.put("msg", ex.getMsg());
        result.put("message", "param error");

        return result;
    }

    /**
     * 权限异常异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ForbidException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public JSONObject paramHandler(ForbidException ex) {
        JSONObject result = new JSONObject();
        result.put("msg", ex.getMsg());
        result.put("message", "无操作权限");

        return result;
    }

    @ResponseBody
    @ExceptionHandler(value = NotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public JSONObject notFound(NotFoundException ex) {
        JSONObject result = new JSONObject();
        result.put("msg", ex.getMsg());
        result.put("message", "找不到资源");

        return result;
    }
}
